package com.simpletour.qa.gateway.jwt;

import com.simpletour.qa.common.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.Date;

/**
 * Json Web Token Util
 * @author zhaohw
 * @date 2018-06-08 14:10
 */
public class JwtTokenUtil {

    private static final Logger logger = LoggerFactory.getLogger(JwtTokenUtil.class);

    //private final static Key SIGNING_KEY = MacProvider.generateKey();

    private final static String SIGNING_KEY = "simple_tour_com";

    private final static Long EXPIRATION_TIME = 7200L;

    /**
     * 生成Token
     * @param user
     * @return
     */
    public static String generateToken(User user){
        Assert.notNull(user,"can not generate jwt with username : null");
        return Jwts.builder()
                .setClaims(ClaimsUtil.getCommonClaims())
                .addClaims(ClaimsUtil.getCustomClaims(user))
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, SIGNING_KEY)
                .compressWith(CompressionCodecs.DEFLATE)
                .compact();
    }

    /**
     * 解析Token
     * @param token
     * @return
     */
    public static Claims getClaimsFromToken(String token){
        return Jwts.parser().setSigningKey(SIGNING_KEY)
                    .requireIssuer(ClaimsUtil.CLAIM_VALUE_ISSUER)
                    .parseClaimsJws(token)
                    .getBody();
    }

    /**
     * 刷新Token
     * @param jwt
     * @return
     */
    public static String refreshToken(String jwt){
        Claims claims = getClaimsFromToken(jwt);
        return  generateTokenByClaims(claims);
    }

    private static String generateTokenByClaims(Claims claims){

        Assert.notNull(claims,"can not generate jwt with claims : null");
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, SIGNING_KEY)
                .compressWith(CompressionCodecs.DEFLATE)
                .compact();
    }

    private static Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + EXPIRATION_TIME * 1000);
    }

}
